package com.mornd.web.controller.common;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;

import com.mornd.common.config.RuoYiConfig;
import com.wf.captcha.*;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.mornd.common.constant.CacheConstants;
import com.mornd.common.constant.Constants;
import com.mornd.common.core.domain.AjaxResult;
import com.mornd.common.core.redis.RedisCache;
import com.mornd.common.utils.uuid.IdUtils;
import com.mornd.system.service.ISysConfigService;

/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@RestController
public class CaptchaController {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysConfigService configService;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled) {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        Captcha captcha = null;
        if ("math".equals(RuoYiConfig.getCaptchaType())) {
            // 使用算数验证码
            captcha = new ArithmeticCaptcha();
            // 运算位数
            captcha.setLen(2);
        } else {
            // 使用字母数字
            captcha = new SpecCaptcha();
            captcha.setLen(4);
        }

        // 图形宽高
        captcha.setWidth(120);
        captcha.setHeight(40);
        //验证码结果
        String captchaResult = captcha.text();

        redisCache.setCacheObject(verifyKey, captchaResult, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        ajax.put("uuid", uuid);
        ajax.put("img", captcha.toBase64());
        return ajax;
    }
}
